package com.example.apple.printingroommanagementsystem;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ClipDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.PopupMenu;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by apple on 17/2/25.
 */
public class userone extends Fragment {
    ListView useroneList;
    Button tab_btn_add_user,弹出删除,弹出编辑,departmentNo,departmentOk;
    EditText 输入帐号,输入密码,输入部门;
    SharedPreferences preferences;
    String token,ip;
    ArrayList<MediaItem>mediaItems;
    MyAdapter myAdapter;
    ImageView xuanzhuantupian1;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.userone_interface_one,container,false);
        useroneList =(ListView) view.findViewById(R.id.userList);
        tab_btn_add_user = (Button) view.findViewById(R.id.tab_btn_add_user);
        preferences =getActivity().getSharedPreferences("ure", Activity.MODE_PRIVATE);
        token = preferences.getString("token","");
        ip = "http://a.xl18z.cn/api/users/list";
        xuanzhuantupian1 = (ImageView)view.findViewById(R.id.xuanzhuantupian1);
        return view;

    }

    @Override
    public void onActivityCreated(@Nullable final Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getUserData();
        popUpResponse(savedInstanceState);
//        tab_btn_add_user.setOnClickListener(new xuanzhuan());
        popUpAdd();
        final Handler handler = new Handler();
        //创建一个Runnable
        Runnable task = new Runnable() {

            public void run() {
                handler.postDelayed(this, 120);
                xuanzhuan();
            }
        };
        handler.post(task);//启动定时器

    }
    public void xuanzhuan(){
        ValueAnimator animator = ValueAnimator.ofFloat(xuanzhuantupian1.getRotationY(),xuanzhuantupian1.getRotationY()+35f);
        animator.setDuration(120).start();
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float current = (float)animation.getAnimatedValue();
                xuanzhuantupian1.setRotationY(current);
                //imageView.setRotationY(current);
            }
        });
    }

    private void popUpAdd() {
        tab_btn_add_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popup(v,"/insert","");
            }
        });
    }

    void popup(View v, final String ip,final String s){
        final View popuview =View.inflate(getContext(),R.layout.userone_add,null);
        final PopupWindow window = new PopupWindow(popuview,1000,950);

        // TODO: 2016/5/17 设置背景颜色
        window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFFFF")));
        // TODO: 2016/5/17 设置可以获取焦点
        window.setFocusable(true);
        // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
        window.setOutsideTouchable(true);
//                window.setBackgroundDrawable(new ClipDrawable(Color.parseColor("#00")));
        //    window.showAtLocation(parent, Gravity.CENTER,20,20);
        window.update();
        window.showAtLocation(v, Gravity.CENTER,0,0);
        departmentOk = (Button)popuview.findViewById(R.id.departmentOk);
        departmentNo =(Button)popuview.findViewById(R.id.departmentNo);
        输入帐号 =(EditText) popuview.findViewById(R.id.输入帐号);
        输入密码=(EditText) popuview.findViewById(R.id.输入密码);
        输入部门=(EditText) popuview.findViewById(R.id.输入部门);
        departmentNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                window.dismiss();
            }
        });
        departmentOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!输入部门.getText().toString().equals("")&&!输入帐号.getText().toString().equals("")&&!输入密码.getText().toString().equals("")){
                    GetRequest get =new GetRequest();
                    String i="?name="+输入帐号.getText().toString()+"&password="+输入密码.getText().toString()+"&department="+输入部门.getText().toString()+"&token="+token;
                        i=i+s;
                    Log.e("-->检测",i);
                    get.doGet("http://a.xl18z.cn/api/users"+ip,i,new Handler(){
                        @Override
                        public void handleMessage(Message msg) {
                            super.handleMessage(msg);
                            getUserData();
                            window.dismiss();
                        }
                    });
                };
            }
        });
    }

    void popUpResponse(final Bundle savedInstanceState){
        useroneList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {
            final TextView ide =(TextView) view.findViewById(R.id.item_id);
            final View popupview = userone.this.getLayoutInflater(savedInstanceState).inflate(R.layout.popupview,null);
            final PopupWindow window = new PopupWindow(popupview,425,120);

            // TODO: 2016/5/17 设置背景颜色
            window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#00000000")));
            // TODO: 2016/5/17 设置可以获取焦点
            window.setFocusable(true);
            // TODO: 2016/5/17 设置可以触摸弹出框以外的区域
            window.setOutsideTouchable(true);
//                window.setBackgroundDrawable(new ClipDrawable(Color.parseColor("#00")));
            //    window.showAtLocation(parent, Gravity.CENTER,20,20);
            window.update();
            window.showAsDropDown(view,300,10);
            弹出删除 = (Button) popupview.findViewById(R.id.弹出删除);
            弹出编辑= (Button)popupview.findViewById(R.id.弹出编辑);
//                弹出编辑.setOnClickListener(new popUpResponseEvent());
//                弹出删除.setOnClickListener(new popUpResponseEvent());
            弹出删除.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    window.dismiss();
                }
            });
            弹出编辑.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    window.dismiss();
                    String idee=ide.getText().toString();
                    popup(v, "/update", "&id="+ide.getText().toString());
                }
            });
            Toast.makeText(getContext(),"tang",Toast.LENGTH_SHORT).show();
        }
    });
        this.registerForContextMenu(useroneList);}
//    @Override
//    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//        super.onCreateContextMenu(menu, v, menuInfo);
//        menu.setHeaderTitle("请选择操作");
//        menu.add(0,1, Menu.NONE,"删除");
//        menu.add(0,2, Menu.NONE,"编辑");
//    }
//
//    @Override
//    public boolean onContextItemSelected(MenuItem item) {
//        switch (item.getItemId()){
//            case 1:
//                deleteDepartMethods(item);
//                break;
//            case 2:
//                editorDepartMethods(item);
//                break;
//        }
//        return super.onContextItemSelected(item);
//    }
//
//    public void editorDepartMethods(MenuItem item) {
//
//    }

    public void deleteDepartMethods(MenuItem item) {
    }


    //    private void showPopupMenu(View view) {
//        // View当前PopupMenu显示的相对View的位置
//        PopupMenu popupMenu = new PopupMenu(getContext(), view);
//        // menu布局
//        popupMenu.getMenuInflater().inflate(R.menu.mian, popupMenu.getMenu());
//        // menu的item点击事件
//        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
//            @Override
//            public boolean onMenuItemClick(MenuItem item) {
//               // Toast.makeText(getApplicationContext(), item.getTitle(), Toast.LENGTH_SHORT).show();
//                return false;
//            }
//        });
//        // PopupMenu关闭事件
//        popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
//            @Override
//            public void onDismiss(PopupMenu menu) {
//             //   Toast.makeText(getApplicationContext(), "关闭PopupMenu", Toast.LENGTH_SHORT).show();
//            }
//        });
//
//        popupMenu.show();
//    }
//    @Override
//    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
//        super.onCreateContextMenu(menu, v, menuInfo);
//        menu.setHeaderTitle("请选择操作");
//        menu.add(0,1, Menu.NONE,"删除");
//        menu.add(0,2, Menu.NONE,"编辑");
//    }
    private void getUserData() {
        GetRequest get = new GetRequest();
        String s = "?token="+token;
        get.doGet(ip,s,new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                mediaItems = new ArrayList<>();
                JSONObject js =(JSONObject) msg.obj;//拿到返回的js对象
                Log.e("de-->",js.toString());
                try {
                    JSONObject jt =  js.getJSONObject("record");
                    JSONArray arr = jt.getJSONArray("data");
                    for (int i =0;i<arr.length();i++){
                        JSONObject jso =  arr.getJSONObject(i);
                        MediaItem mediaItem = new MediaItem();
                        mediaItem.id = jso.getString("id");
                        mediaItem.name = jso.getString("name");
                        if (!(jso.length() <=2)){
                            mediaItem.department =jso.getString("department");
                        }else {
                            mediaItem.department = "无部门";
                        }
//
                        //把封装好的mediaItem模型加进mediaItems;
                        mediaItems.add(mediaItem);
                        useroneList.setAdapter(myAdapter);
                        myAdapter = new MyAdapter(getContext(),mediaItems);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

//    private class xuanzhuan implements View.OnClickListener {
//        @Override
//        public void onClick(View v) {
//            ValueAnimator animator = ValueAnimator.ofFloat(xuanzhuantupian1.getRotationY(),xuanzhuantupian1.getRotationY()+35f);
//            animator.setDuration(30).start();
//            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
//                @Override
//                public void onAnimationUpdate(ValueAnimator animation) {
//                    float current = (float)animation.getAnimatedValue();
//                    xuanzhuantupian1.setRotationY(current);
//                    //imageView.setRotationY(current);
//                }
//            });
//        }
//    }


//    private class popUpResponseEvent implements View.OnClickListener {
//        @Override
//        public void onClick(View v) {
//            switch (v.getId()){
//                case R.id.弹出删除:
//
//                    break;
//            }
//        }
//    }
}
